using MediatR;
using Microsoft.EntityFrameworkCore;
using Traceability.API.APPLications.Commands.TraceabilityInfoshow;
using Traceability.API.Services;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.API.APPLications.CommandHanders.TraceabilityInfoshow
{
    /// <summary>
    /// 更新溯源信息命令处理程序
    /// </summary>
    public class UpdateTraceabilityInfoCommandHandler : IRequestHandler<UpdateTraceabilityInfoCommand, APIResult<bool>>
    {
        private readonly IBaseRepository<TraceabilityInfo> _traceabilityRepository;
        private readonly TraceabilityRedisHelper _redisHelper;
        private readonly ILogger<UpdateTraceabilityInfoCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="traceabilityRepository">溯源信息仓储</param>
        /// <param name="redisHelper">Redis帮助类</param>
        /// <param name="logger">日志记录器</param>
        public UpdateTraceabilityInfoCommandHandler(
            IBaseRepository<TraceabilityInfo> traceabilityRepository,
            TraceabilityRedisHelper redisHelper,
            ILogger<UpdateTraceabilityInfoCommandHandler> logger = null)
        {
            _traceabilityRepository = traceabilityRepository;
            _redisHelper = redisHelper;
            _logger = logger;
        }

        /// <summary>
        /// 处理更新请求
        /// </summary>
        /// <param name="request">更新请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>更新结果</returns>
        public async Task<APIResult<bool>> Handle(UpdateTraceabilityInfoCommand request, CancellationToken cancellationToken)
        {
            APIResult<bool> result = new APIResult<bool>();
            try
            {
                _logger?.LogInformation("更新请求: ID={0}, ModifiedBy={1}", request.TraceabilityId, request.ModifiedBy);

                // 参数验证
                if (request.TraceabilityId <= 0)
                {
                    result.Code = APIEnum.操作失败;
                    result.Message = "无效的TraceabilityId";
                    return result;
                }

                // 查找要更新的记录
                var query = _traceabilityRepository.GetAll()
                    .Where(t => t.TraceabilityId == request.TraceabilityId);

                // 记录查询
                string sql = $"查询条件: TraceabilityId={request.TraceabilityId}";
                _logger?.LogInformation("更新SQL查询: {0}", sql);

                var traceability = await query.FirstOrDefaultAsync(cancellationToken);

                if (traceability == null)
                {
                    result.Code = APIEnum.查询失败;
                    result.Message = "记录不存在";
                    _logger?.LogWarning("尝试更新不存在的记录: ID={0}", request.TraceabilityId);
                    return result;
                }

                // 更新字段
                traceability.ProductId = request.ProductId;
                traceability.ProductionBatch = request.ProductionBatch;
                traceability.ShelfLife = request.ShelfLife;
                traceability.ProductionLicenseNumber = request.ProductionLicenseNumber;
                traceability.ManufacturerName = request.ManufacturerName;
                traceability.InformationCompleteness = request.InformationCompleteness;
                traceability.PhotoUrl = request.PhotoUrl;
                traceability.ModifiedBy = request.ModifiedBy;
                traceability.ModifiedTime = DateTime.Now;

                // 保存更改
                var updateResult = await _traceabilityRepository.Update(traceability);
                
                _logger?.LogInformation("更新数据库更新结果: {0}", updateResult);

                if (updateResult <= 0)
                {
                    result.Code = APIEnum.更新失败;
                    result.Message = "数据库更新失败";
                    return result;
                }

                // 更新Redis缓存
                var redisResult = await _redisHelper.UpdateTraceabilityInfoAsync(traceability);
                _logger?.LogInformation("更新Redis缓存更新结果: {0}", redisResult);
                
                // 清除列表缓存，以便下次获取最新数据
                await _redisHelper.RemoveTraceabilityListAsync();

                result.Code = APIEnum.更新成功;
                result.Message = "记录已成功更新";
                result.Data = true;
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "更新处理时发生异常: ID={0}", request.TraceabilityId);
                result.Code = APIEnum.更新失败;
                result.Message = ex.Message;
                result.Data = false;
            }
            return result;
        }
    }
} 